package week05.necessary.jdbc;

import lombok.extern.slf4j.Slf4j;
import week05.necessary.jdbc.base.AbstractJdbcExampleImpl;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 事务操作
 */
@Slf4j
public class TransactionJdbcOperator extends AbstractJdbcExampleImpl {
    @Override
    public void executeWithTransaction(String... sqls) throws SQLException {
        Connection connection = getConnection();
        boolean previousAutoCommit = connection.getAutoCommit();

        Statement statement = null;
        try {
            connection.setAutoCommit(false);
            statement = connection.createStatement();
            for (String sql : sqls) {
                statement.addBatch(sql);
            }

            statement.executeBatch();
            connection.commit();
        } catch (SQLException exception) {
            connection.rollback();
            throw exception;
        } finally {
            connection.setAutoCommit(previousAutoCommit);
            if (statement != null) {
                statement.close();
            }
            connection.close();
        }
    }
}
